<#assign packageName = content.items.controller.packageName>
<#assign tableName = content.content.tableName>
<#assign lowerName = content.content.lowerName>
<#assign camelName = content.content.camelName>
<template>
  <el-dialog :title="getTitle()" :visible.sync="visible" append-to-body width="80%" @close="closeDialog">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" label-position="right">
      <el-row>
        <!-- -------------------------------------表单内容------------------------------------- -->
                <#assign treeNum = 0><#--弹框树的数量-->
                <#assign gridNum = 0><#--弹框列表的数量-->
                <#assign dateNum = 0><#--日期输入框的数量-->
                <#assign timeNum = 0><#--时间输入框的数量-->
                <#list content.content.fields as item>
                <#if item.primary != true>
                <#if item.length?default(0)<500>
                <#if item.fieldName?lower_case?contains("time")>
                 <#assign timeNum = timeNum+1 >
        <!--时间输入框-->
        <el-col :span="8">
          <el-form-item label="<#if item.fieldRemark??>${item.fieldRemark}</#if>" prop="${item.fieldName}">
            <el-date-picker v-model="form.${item.fieldName}"  @change="handleDatePicker('${item.fieldName}',$event)"  value-format="yyyy-MM-dd" type="datetime"  :disabled="isDisabled()" placeholder="请输入<#if item.fieldRemark??>${item.fieldRemark}</#if>" style="width: 100%"/>
          </el-form-item>
        </el-col>
                <#elseif item.fieldName?lower_case?contains("date") && item.fieldName?lower_case != 'updateby'>
                <#assign dateNum = dateNum+1 >
        <!--日期输入框-->
        <el-col :span="8">
          <el-form-item label="<#if item.fieldRemark??>${item.fieldRemark}</#if>" prop="${item.fieldName}">
            <el-date-picker v-model="form.${item.fieldName}"  @change="handleDatePicker('${item.fieldName}',$event)"  value-format="yyyy-MM-dd" type="date"  :disabled="isDisabled()" placeholder="请输入<#if item.fieldRemark??>${item.fieldRemark}</#if>" style="width: 100%"/>
          </el-form-item>
        </el-col>
                <#elseif item.fieldName?lower_case?contains("status")  || item.fieldName?lower_case?contains("type")>
        <!--选择框-->
        <el-col :span="8">
          <el-form-item label="<#if item.fieldRemark??>${item.fieldRemark}</#if>" prop="${item.fieldName}">
            <el-select v-model="form.${item.fieldName}" placeholder="请选择<#if item.fieldRemark??>${item.fieldRemark}</#if>" style="width: 100%" :disabled="isDisabled()" clearable>
              <el-option v-for="item in getSelects('flowstatus')" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"/>
            </el-select>
          </el-form-item>
        </el-col>
                <#elseif item.fieldName?lower_case?contains("deptid") || item.fieldName?lower_case?contains("orgid")>
                <#assign treeNum = treeNum+1 >
        <!--定位树-->
        <el-col :span="8">
          <el-form-item label="<#if item.fieldRemark??>${item.fieldRemark}</#if>" prop="${item.fieldName}">
            <el-input v-model="form.${item.fieldName}Disp"  @focus="handleTreeFocus(location.treeconfig,form.${item.fieldName})" :disabled="isDisabled()" placeholder="请选择<#if item.fieldRemark??>${item.fieldRemark}</#if>"/>
          </el-form-item>
        </el-col>
                <#elseif item.fieldName?lower_case?contains("updateby") || item.fieldName?lower_case?contains("createby")  || item.fieldName?lower_case?contains("user")>
                <#assign gridNum = gridNum+1 >
        <!--定位列表-->
        <el-col :span="8">
          <el-form-item label="<#if item.fieldRemark??>${item.fieldRemark}</#if>" prop="${item.fieldName}">
            <el-input v-model="form.${item.fieldName}Disp" @focus.stop="handleListFocus(location.gridconfig,form.${item.fieldName})" :disabled="isDisabled()" placeholder="请选择<#if item.fieldRemark??>${item.fieldRemark}</#if>"/>
          </el-form-item>
        </el-col>
                <#else>
        <!--文本输入框-->
        <el-col :span="8">
          <el-form-item label="<#if item.fieldRemark??>${item.fieldRemark?default("")}</#if>" prop="${item.fieldName}">
            <el-input v-model="form.${item.fieldName}" placeholder="请输入<#if item.fieldRemark??>${item.fieldRemark?default("")}</#if>" maxlength="${item.length?default(0)}" :readonly="false" :disabled="isDisabled()" clearable/>
          </el-form-item>
        </el-col>
                </#if>
                <#else>
        <!--文本域-->
        <el-col :span="8">
          <el-form-item label="<#if item.fieldRemark??>${item.fieldRemark}</#if>" prop="${item.fieldName}">
            <el-input v-model="form.${item.fieldName}" type="textarea" :row="5" :disabled="isDisabled()" />
          </el-form-item>
        </el-col>
                </#if>
                </#if>
                </#list>
      </el-row>
    </el-form>

    <!--文件上传-->
    <div>
      <h5 class="titleName">附件列表</h5>
        <ibp-attachment ref="customupload" :total-size="totalSize" :show-btn="dialogType !== 'check'? true : false" :single-size="singleSize" :file-suff="fileSuff" :apptype="apptype"/>
    </div>

    <!--操作按钮-->
    <div slot="footer" class="dialog-footer" v-if="dialogType !== 'check'" >
        <el-button @click="closeDialog">关 闭</el-button>
        <el-button @click="handleSave">保 存</el-button>
    </div>

    <#if treeNum != 0><!--定位树组件--></#if>
    <#if treeNum != 0><select-tree ref="locationTree" @locationTreeSelected="locationTreeSelected"/></#if>
    <#if gridNum != 0><!--定位列表--></#if>
    <#if gridNum != 0><select-list ref="locationList" @locationChecked="locationChecked"></select-list></#if>
  </el-dialog>
</template>
<script>
import IbpAttachment from '@/views/components/IbpAttachment/index.vue'
<#list "${packageName}"?split(".") as package>
<#if package!="com" && package!="ibp" && package!="controller">
<#if treeNum != 0>import SelectTree from '@/components/locationTree'</#if>
<#if gridNum != 0>import SelectList from '@/views/example/location/locationList'</#if>
import {add${camelName?cap_first},edit${camelName?cap_first}} from '@/api/${package}/${package}'
</#if>
</#list>


export default {
  name: 'addModule',
  components: {<#if treeNum != 0>SelectTree,</#if><#if gridNum != 0>SelectList,</#if>IbpAttachment},
  props: {<#--上级组件传递的属性-->
    show: {
      type: Boolean,
      default: false
    },
    dialogType: {
      type: String
    }
  },
  data() {
    return {
      form: {
            <#list content.content.fields as item>
            <#if item.primary == true>
            <#else>
        ${item.fieldName}: ''<#if item?has_next>,</#if>
            </#if>
            </#list>
      },
      rules: { //规则校验
            <#list content.content.fields as item>
            <#if item.primary == true>
            <#else>
        ${item.fieldName}: [{required: true,message: '请输入<#if item.fieldRemark??>${item.fieldRemark}</#if>',trigger: 'blur'}]<#if item?has_next>,</#if>
            </#if>
            </#list>
      },
      <#if content.content.primaryField??>
      <#assign assign_idFieldName = content.content.primaryField[0].fieldName>
      ${assign_idFieldName}:'',//主键ID
      </#if>
      /*****附件相关*******/
      apptype: '${camelName}',
      businesskey: '',
      fileSuff: '',//固附件后缀
      singleSize: '',//单个附件上传大小
      totalSize: '',//附件大小
      /*****下拉框*****/
      selectDict: [
        {dictValue:'1',dictLabel:'选项1'},
        {dictValue:'2',dictLabel:'选项2'},
        {dictValue:'3',dictLabel:'选项3'}
      ],
            <#if treeNum != 0 || gridNum != 0>
      /*****定位配置*******/
      location: {
        <#if treeNum != 0>
        treeconfig: {//树形选择配置
          menuid: 'getOrgansTree',
          title: '选择树',
          checkType: 'radio', // checkbox
          prop: {
            label: 'createDeptidDisp',//页面展示值,需在后台转码查询 <#--替换相应的字段,这个值要在后台转码后,列表查询出来,修改时才能回显,${item.fieldName}name-->
            value: 'createDeptid'//数据库字段 <#--替换相应的字段 ${item.fieldName}-->
          },
          lastChild: false,
          parentLinkage: true,
          params: {
            //upOrganKey: this.$store.state.user.userUpOrgan,
          }
        },
            </#if>
            <#if gridNum != 0>
        gridconfig: {//表格选择配置
          menuid: 'getUserForGrid',
          title: '选择列表',
          checkType: 'checkbox', // radio
          tableColumn: [''],
          prop: {
            label: 'createByDisp',//页面展示值,需在后台转码查询 <#--替换相应的字段,这个值要在后台转码后,列表查询出来,修改时才能回显-->
            value: 'createBy'//数据库字段 <#--替换相应的字段-->
          },
        }
            </#if>
      },
            </#if>
    }
  },
  computed: {
    visible: {
      get() {
        return this.show
      },
      set(val) {
        this.$emit('update:show', val)
      }
    },
    themesize() {
      return this.$store.state.settings.size
    },
  },
  created() {
    // 下拉选
    //this.getDicts('字典key').then((response) => {
    // this.selectDict = response.data
    // })

    // 获取附件上传支持后缀
    this.getConfigKey('sys.attach.fileSuff').then((response) => {
      this.fileSuff = response.msg
    })
     // 获取附件上传单文件大小
    this.getConfigKey('sys.attach.singleSize').then((response) => {
      this.singleSize = response.msg
    })
    // 获取附件上传全部文件大小
    this.getConfigKey('sys.attach.totalSize').then((response) => {
      this.totalSize = response.msg
    })
  },
  watch: {<#--上属性监听-->
    dialogType: {
      handler(nVal) {
        if (nVal === 'add') {
          this.form.createByDisp = this.$store.state.user.realname
          this.form.createBy = this.$store.state.user.name
          this.form.createDeptid= this.$store.state.user.userOrgan
          this.form.createDeptidDisp= this.$store.state.user.userOrganName
          this.getNowDate();//获取当前时间
        }
      },
      deep: true
    }
  },

  methods: {
    // 下拉框数据
    getSelects(prop) {
      if (prop === 'flowstatus') return this.selectDict
    },
    // 保存
    handleSave() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          // 新增
          if (this.dialogType === 'add') {
                    <#if content.content.primaryField??>
                    <#assign assign_idFieldName = content.content.primaryField[0].fieldName>
            const data = Object.assign({}, this.form, {${assign_idFieldName}: this.${assign_idFieldName}})
                    </#if>
            add${camelName?cap_first}(data).then(res => {
              if (res.code === 200) {
                this.$message({type: 'success', message: '保存成功！'})
                  this.$parent.getList()
                            <#if content.content.primaryField??>
                            <#assign assign_idFieldName = content.content.primaryField[0].fieldName>
                  this.businesskey = res.data.${assign_idFieldName}
                            </#if>
                  let uploadFileList = this.$refs['customupload'].uploadFileList
                  if (uploadFileList.length > 0) {
                    this.$refs['customupload'].handleUpdataBusinesskey(this.businesskey)//更新businesskey
                  }
                  this.closeDialog()
              } else {
                this.$message({type: 'error', message: '保存失败！'})
              }
            })
          }
          else {
            //修改
            const data = Object.assign({}, this.form)
            edit${camelName?cap_first}(data).then(res => {
              if (res.code === 200) {
                this.$message({type: 'success', message: '保存成功！'})
                this.$parent.getList()
                this.closeDialog()
              } else {
                this.$message({type: 'error', message: '保存失败！'})
              }
            })
          }
        }
      })
    },
    getForm(data) {
      this.form = Object.assign({}, data)
        <#if content.content.primaryField??>
        <#assign assign_idFieldName = content.content.primaryField[0].fieldName>
      this.${assign_idFieldName} = this.form.${assign_idFieldName}
      this.$nextTick(() => {
        this.$refs['customupload'].handleGetFileList(data.${assign_idFieldName}, '${camelName}')//附件attachtype
      })
       </#if>
    },
    //新增时生成主键
    getRandomID(id) {
      this.${assign_idFieldName} = id
      this.$nextTick(() => {
        this.$refs['customupload'].handleGetFileList(id, '${camelName}')
      })
    },
    // 弹窗title
    getTitle() {
      let title = this.dialogType === 'add' ? '新增' : '修改'
      if(this.dialogType === 'check') {
        title = '详情'
      }
      return title
    },
    // 禁用处理
    isDisabled() {
      if(this.dialogType === 'check') return true
    },
    <#if treeNum != 0>
    // 定位树
    handleTreeFocus(focusData, val) {
      this.$refs.locationTree.openDialog(focusData, val)
    },
    // 定位树选中的内容
    locationTreeSelected(data) {
      const {selectionName, selectionId, prop: {label, value}} = data
      this.$set(this.form, label, selectionName)
      this.$set(this.form, value, selectionId)
    },
    </#if>
    <#if gridNum != 0>
    // 定位列表
    handleListFocus(focusData,val) {
      this.$refs['locationList'].openLocationListDislog(focusData,val)
    },
    // 定位列表选中的值
    locationChecked(checkedVal) {
      const {param: {checkType,prop: {label,value}},rows,list} = checkedVal
      this.$set(this.form,label,rows.checkedVal1)
      this.$set(this.form,value,rows.checkedVal0)
    },
    </#if>
    <#if dateNum != 0 || timeNum != 0 >
    //日期处理
    handleDatePicker(prop, val) {
      let newDate = new Date()
      const year = newDate.getFullYear()
      const month = newDate.getMonth() + 1
      const day = newDate.getDate()
      let currentDate = year+'-'+month+'-'+day
      let vDate = new Date(val)
      let cDate = new Date(currentDate)
      if (vDate.getTime() > cDate.getTime()) {
        //this.$set(this.form, '日期字段', '1')
      }
    },
    //查询当天日期
    getNowDate(){
      const timeOne = new Date()
      const year = timeOne.getFullYear()
      let month = timeOne.getMonth() + 1
      let day = timeOne.getDate()
      month = month < 10 ? '0' + month : month
      day = day < 10 ? '0' + day : day
      this.form.createTime=  year+'-'+month+'-'+day
    },
    </#if>
    // 关闭弹框
    closeDialog() {
      this.$refs.form.resetFields()
      this.$emit('update:show', false)//visible
    },
  }
}
</script>
<style scoped lang="scss">
</style>
